import { HubConnectionBuilder, HubConnection, HttpTransportType, HubConnectionState } from '../libs/signalr/signalr';

import GameWS from "./GameWS";

import FireBaseMgr from "./FireBaseMgr"

import LanguageMng from "./LanguageMng";
import GameDataUtilTs from "../Utils/GameDataUtilTs";
import NotificationMgr from "./NotificationMgr";
import LogicConfigTs from '../Utils/LogicConfigTs';
cc.Class({
    extends: cc.Component,

    properties: {
        uiMgr:{
            default:null,
            type:require("LobbyUIMgr")
        }
    },

    onLoad () {
        this.node.on("lobby_player_count_select_clicked",this._onPlayerCountSelect.bind(this), this)
        this.node.on("server_find_room",this._onFindRoom.bind(this),this)
        this.node.on("refresh_activity",this.refreshGetActivityStatus.bind(this),this)
        this.node.on("refresh_player_info",this.refreshUserInfo.bind(this),this)
        // this.node.on("refresh_player_info",this.refreshUserInfo.bind(this),this)


        let updatePeople = async function () {
            cc.log("计时器运行：this.udtPp")
            let result = await cc.gg.httpUtil.httpGet('/user/statistics')
            if(!result.succ){
                cc.error(result.msg)
            }else {
                cc.gg.dataMgr.statistics = result.data
                //加个判断，为防止有时onDestroy会在游戏场景出来之后才运行
                let contentNode = cc.find("Canvas/content")
                if(contentNode) contentNode.emit("ui_update_people")
            }
        }
        updatePeople()
        if(this.udtPp){
            this.unschedule(this.udtPp)
        }
        this.udtPp = updatePeople.bind(this)
        this.schedule(this.udtPp, 60)

        if(NotificationMgr.FristGet == true) {
            cc.gg.httpUtil.httpGet('/notification/list/get', null, (result) => {
                if (!result.succ) {
                } else {
                    if(result.data.length > 0) {
                        cc.gg.toastMgr.showScroll(result.data , null);
                        NotificationMgr.setSystemArr(result.data);
                        NotificationMgr.FristGet = false;
                    }
                }
            });
        }
        
        // cc.gg.toastMgr.showScroll(result.data , null);
        // cc.gg.toastMgr.showScroll(null, { type: 1, args: "xiaoming , 1000" })
        // cc.gg.toastMgr.showScroll(null , {type , args})
        // this.startStatisticHeartBeat(60)
        // this.refreshGetActivityStatus()
    },

    refreshGetActivityStatus:function () {
        cc.gg.httpUtil.httpGet('/activities/status/get',{activityId:1001},function (result) { 
            if(!result.succ){
                cc.error(result.msg)
            }else {
                let data = result.data
                cc.log("get activities data:",data)
                cc.log(JSON.stringify(result))
                let status = data.status    //bind mobile
                let record = data.data
                let count = record.count
                let ts = record.ts
                let rewards = data.rewards[count]
                let done = data.done
                let activityParent = cc.find("Activities",this.node)
                activityParent.removeAllChildren()
                if(!done){
                    if(status === 0){
                        if(count !== 3){
                            // let showData = data.reward[count]
                            // let showCollectButton = !data.done
                            // cc.find("Canvas/UIManager").emit("ui_show_activity",showData,showCollectButton)

                            //todo show title notice
                            cc.loader.loadRes("Activity/DailyNotice",cc.Prefab,function (err, prefab) {
                                if(err){
                                    cc.error(err)
                                    return
                                }
                                let newNode = cc.instantiate(prefab)
                                activityParent.addChild(newNode)
                                if(count === 1){
                                    newNode.getComponent("DailyNotice").showDay1Notice()
                                }else if(count === 2){
                                    newNode.getComponent("DailyNotice").showDay2Notice()
                                }else{
                                    newNode.getComponent("DailyNotice").showDay3Notice()
                                }
                            }.bind(this))

                            //todo check can collect and do it
                            let canCollect = this.canCollect(ts)
                            if(canCollect){
                                cc.gg.toastMgr.showActivityDialog({day:count+1,coin:rewards.coin},function () {
                                    cc.gg.toastMgr.removeActivityDialog()
                                    this.doActivityCollect()
                                }.bind(this))
                            }
                        }
                    }else if(status === 1){
                        cc.loader.loadRes("Activity/DailyBindNotice",cc.Prefab,function (err, prefab) {
                            if(err){
                                cc.error(err)
                                return
                            }
                            let newNode = cc.instantiate(prefab)
                            activityParent.addChild(newNode)
                        }.bind(this))
                    }else {
                        cc.error("Unknown activity status:",status)
                    }
                }else {
                    cc.logfl("All activity is done.")
                }
            }
        }.bind(this))
    },

    doActivityCollect:function () {
        cc.gg.toastMgr.showNetWaitting(function () {
            cc.gg.httpUtil.httpPost("/activities/collect",{activityId:1001},function (result) {
                cc.gg.toastMgr.removeNetWaitting()

                if (!result.succ) {
                    cc.error(result.msg)
                    return
                }

                this.refreshUserInfo()
                this.refreshGetActivityStatus()

            }.bind(this))
        }.bind(this))
    },

    canCollect:function (ts) {
        var timestamp = (new Date()).getTime()/1000;
        let nowT = Math.floor(timestamp / 86400)
        let lastT = Math.floor(ts / 86400)
        let canCollect = nowT !== lastT;
        cc.log("lastT:",lastT)
        cc.log("nowT:",nowT)
        return canCollect
    },

    startStatisticHeartBeat:function (perSecond) {
        if(this.heartBeatFunc) clearTimeout(this.heartBeatFunc)
        this.heartBeatFunc = function(){//https://api.khelochalo.com:20050/user/heartbeat?uid=8000
            cc.gg.httpUtil.httpGetWithWholeUrl('https://api.khelochalo.com:20050/user/heartbeat',
                {uid:cc.gg.dataMgr.getPlayerId()},
                function (result) {
                // cc.log("心跳返回值：",result)
            })
        }.bind(this)
        setTimeout(this.heartBeatFunc,perSecond * 1000)
    },

    onDestroy(){
        cc.log("已经停止了计时器：this.udtPp")
        this.unschedule(this.udtPp)
    },

    start () {
        this.refreshUserKYCData()
        this.refreshUserInfo()
        this._checkIsKicked()
    },

    _checkIsKicked:function () {
        if(GameDataUtilTs.isKickCauseNoMoney){
            cc.gg.logicUtil.showKickByGold()
        }
    },

    refreshUserKYCData:function () {
        cc.gg.httpUtil.httpGet('/user/doc/kyc/get',null,function (result) {
            if(!result.succ){
                cc.error(result.msg)
            }else {
                cc.gg.dataMgr.kycData = result.data
            }
        }.bind(this))
    },


    async refreshUserInfo () {
        let result = await cc.gg.httpUtil.httpGet('/user/profile/get')
        if(!result.succ){
            cc.error("获取用户信息失败：",result.msg)
            cc.gg.httpUtil.setUserToken(null)
            cc.gg.gameDataUtil.goToLogin(true)
        }else {
            result.data.face_bg = Math.random()*1000000
            cc.logfl("get user info success:",result.data)
            cc.gg.dataMgr.setPlayerInfo(result.data)
            if(cc.gg.gameDataUtil.isKicked){
                cc.log("因为是被踢出来的，所以直接按没有房间算，不重连")
                cc.gg.gameDataUtil.isKicked = false
                cc.gg.dataMgr.isReconnect = false
            }
            if(cc.gg.dataMgr.room && !GameDataUtilTs.isKickCauseNoMoney){
                cc.log("检测到玩家仍有房间，开始重连回去：游戏初始化时使用重连模式")
                cc.gg.dataMgr.isReconnect = true
                // GameWS.connect(url);
                cc.gg.dataMgr.room.openRoom()
            }else {
                if(GameDataUtilTs.isKickCauseNoMoney)
                    GameDataUtilTs.isKickCauseNoMoney = false

                this.uiMgr.updateLobbyUser()
                this.scheduleOnce(function () {
                    if(cc.gg.gameDataUtil.isRegister){
                        cc.gg.gameDataUtil.isRegister = false
                        this.uiMgr.openUserConfig()
                    }
                }.bind(this),0)
            }
        }
    },

    update (dt) {
        this._checkOldGame()
    },

    _checkOldGame:function (dt) {
        if(cc.gg.dataMgr.room && cc.gg.dataMgr.getPlayerUser()){
            if(!this._openingRoom){
                cc.gg.dataMgr.room.openRoom()
                this._openingRoom = true
            }
        }
    },

    onPlayButtonClicked:function (event) {
        let btnName = event.target.name
        if(btnName === "BtnClearStorage"){
            cc.sys.localStorage.removeItem("user_token")
        }
    },

    _onPlayerCountSelect:function (playerCount) {
        this.playerCount = playerCount
        let lobbyContent = cc.find("Canvas/content").getComponent("LobbyContent")
        if(lobbyContent.nowTab === "button_howtoplay"){
            lobbyContent.nowTab = "button_points"
        }
        lobbyContent._selectTab(lobbyContent.nowTab)
        // cc.find("Canvas/content").emit("ui_update_tab")
    },

    async _onFindRoom (roomObj) {
        let self = this
        cc.log("尝试寻找房间：",roomObj)
        // this.openGameScene(roomObj.id)

        let wsEnable = await self._checkWS()
        if(!wsEnable){
            await cc.gg.toastMgr.showNetWaitting()
            cc.log("目前socket未连接，等待连接上")

            cc.find("Canvas").emit("msgwatcher_add",function () {
                if(GameWS.getState() === HubConnectionState.Connected){
                    cc.log("socket连接上了，开始寻找room")
                    self._doFindRoom(roomObj)
                    return true
                }
                return false
            }.bind(self))
        }else {
            await cc.gg.toastMgr.showNetWaitting()
            self._doFindRoom(roomObj)
        }
    },


    openGameScene(mode){
        let roomMode = cc.gg.enumConfig.RoomMode
        let modeBase = mode & 0x0f0
        if(modeBase === roomMode.BASE_VALUE_2){
            cc.log("进入场景2")
            cc.gg.gameDataUtil.goToTwoPlayerGame()
        }else if(modeBase === roomMode.BASE_VALUE_6){
            cc.log("进入场景6")
            cc.gg.gameDataUtil.goToSixPlayerGame()
        }
    },

    async _doFindRoom(roomObj){
        let type = roomObj.type
        let mode = roomObj.id
        let joker = true
        LogicConfigTs.LAST_ENTERED_ROOM = roomObj.id;
        let code = await GameWS.findRoom(type, mode, joker)
        if(!code){//success
            cc.gg.gameDataUtil.roomInfo = roomObj
            // cc.find("Canvas").emit("msgwatcher_add",function () {
            //     if(cc.gg.dataMgr.room){
            //         cc.gg.dataMgr.room.openRoom()
            //         return true
            //     }
            //     return false
            // }.bind(this))
        }else if(code == 2){//already has a room
            this._findRoomFailed(code)
        }
        else {
            cc.gg.toastMgr.removeNetWaitting()
            this._findRoomFailed(code)
        }
    },

    async _checkWS () {
        let wsStatus = GameWS.getState()
        cc.log(" 检查ws状态：",wsStatus)
        if(wsStatus !== HubConnectionState.Connected){
            return false
        }

        return true
    },

    _findRoomFailed:function (code) {
        if(code == 2){
            cc.logfl("已经在游戏中了")
            // this.__showReconnectRoomAsk()
        }else if(code == 5){
            let title = LanguageMng.getSentence(3)
            let btnStr = LanguageMng.getSentence(179)
            let buyStr = LanguageMng.getSentence(182)
            let contentStr = LanguageMng.getSentence(180)
            let cb = function () {
                cc.gg.toastMgr.removeDialog()
            }.bind(this)
            // cc.gg.toastMgr.showDialogOneButton(title,btnStr,contentStr,cb)

            cc.gg.toastMgr.showDialog(title,buyStr,btnStr,contentStr,
                function () {
                    cc.gg.tdUtil.doSendTdEvent("show_wallet","MoneyNotEnough")
                    cc.gg.toastMgr.removeDialog()
                    this.uiMgr.tryToShowWallet()
                }.bind(this),
                cb
            )
        }
    },

    __showReconnectRoomAsk:function () {
        let title = LanguageMng.getSentence(3)
        let btnStr = "Return"
        let buyStr = "Quit"
        let contentStr = "You own a room,do you want to go back or quit it?"
        let cb = function () {
            cc.gg.toastMgr.removeDialog()
            cc.gg.dataMgr.getPlayerUser().leave()
        }.bind(this)
        // cc.gg.toastMgr.showDialogOneButton(title,btnStr,contentStr,cb)

        cc.gg.toastMgr.showDialog(title,buyStr,btnStr,contentStr,
            async function () {
                await cc.gg.toastMgr.showNetWaitting()
                cc.gg.toastMgr.removeDialog()

                cc.warn("重连到已有房间")
            }.bind(this),
            cb
        )
    },

    showLobbyRed:function () {
        cc.director.loadScene("LobbyRed")
    }
});
